<template>
  <div >
    <!-- 日期选择 -->
    <el-date-picker
      v-model="day"
      type="date"
      placeholder="选择日期"
      @change="getDaySummary"
      align="center">
    </el-date-picker>

    <!-- 分割线 -->
    <md-divider></md-divider>

    <!-- 任务总数，任务完成个数，任务查看 -->
    <md-table v-model="searched" md-sort="name" md-sort-order="asc"  md-fixed-header>
      <!-- 注意，这个在下面竟然没效果 -->
      Tasks 完成/总任务 {{done}}/{{all}}
      <md-table-toolbar>
        <div class="md-toolbar-section-start">
          <h1 class="md-title">Tasks 完成/总任务（{{done}}/{{all}}）</h1>
        </div>

        <md-field md-clearable class="md-toolbar-section-end">
          <md-input placeholder="Search by content..." v-model="search" @input="searchOnTable" />
        </md-field>
      </md-table-toolbar>

      <md-table-empty-state
        md-icon="free_breakfast"
        md-label="没有日志"
        :md-description="`查询'${search}' 为空。请重新查询！`">
        <!--<md-button class="md-primary md-raised" @click="newUser">Create New User</md-button>-->
      </md-table-empty-state>

      <md-table-row slot="md-table-row" slot-scope="{ item }">
        <md-table-cell md-label="任务内容" md-sort-by="content" md-numeric>{{ item.content }}</md-table-cell>
        <md-table-cell md-label="开始时间" md-sort-by="startTime">{{ item.startTime }}</md-table-cell>
        <md-table-cell md-label="结束时间" md-sort-by="endTime">{{ item.endTime }}</md-table-cell>
        <md-table-cell md-label="重要性" md-sort-by="importanceValue">{{ item.importanceValue }}</md-table-cell>
      </md-table-row>
    </md-table>

    <!-- 分割线 -->
    <md-divider class="md-inset"></md-divider>

    <!-- 未完成任务-->
    <md-table v-model="notDoneTasks"  @md-selected="onSelect">
      <!-- 同样的道理，这个在下面也有问题 -->
      Tasks 未完成/总任务（{{all-done}}/{{all}}）
      <md-table-toolbar>
        <h1 class="md-title">Tasks 未完成/总任务（{{all-done}}/{{all}}）</h1>
      </md-table-toolbar>

      <md-table-toolbar slot="md-table-alternate-header" slot-scope="{ count }">
        <div class="md-toolbar-section-start">{{ getAlternateLabel(count) }}</div>

        <div class="md-toolbar-section-end">
          <md-button @click="addNotDoneTasksToTomorrow" class="md-icon-button">
            <md-icon>add_box</md-icon>
          </md-button>
        </div>
      </md-table-toolbar>

      <md-table-row slot="md-table-row" slot-scope="{ item }"  md-selectable="multiple" md-auto-select>
        <md-table-cell md-label="任务内容" md-sort-by="content" md-numeric>{{ item.content }}</md-table-cell>
        <md-table-cell md-label="开始时间" md-sort-by="startTime">{{ item.startTime }}</md-table-cell>
        <md-table-cell md-label="结束时间" md-sort-by="endTime">{{ item.endTime }}</md-table-cell>
        <md-table-cell md-label="重要性" md-sort-by="importanceValue">{{ item.importanceValue }}</md-table-cell>
      </md-table-row>
    </md-table>
    <!-- 提示框-->
    <Message ref="mes"></Message>
  </div>
</template>

<script>
  import 'element-ui/lib/theme-chalk/index.css'
  import {queryCount, queryDaySummary, queryNotDoneTask} from '@/util/service/JournalService'
  import Message from '@/components/Message'
  import {bulkAddTasks} from '@/util/service/TaskService'

  const toLower = text => {
    return text.toString().toLowerCase()
  }

  const searchByContent = (items, term) => {
    if (term) {
      return items.filter(item => toLower(item.content).includes(toLower(term)))
    }

    return items
  }

  export default {
    name: 'Day',
    components: {Message},
    data: () => ({
      day: new Date(),
      search: null,
      searched: [],
      all: null, // 所有的任务
      done: null, // 已经完成任务
      tasks: [{content: 'xx', startTime: 'yy', endTime: 'zz', importanceValue: 'jj'},
        {content: 'xx', startTime: 'yy', endTime: 'zz', importanceValue: 'jj'},
        {content: 'xx', startTime: 'yy', endTime: 'zz', importanceValue: 'jj'}
      ],
      notDoneTasks: [],
      selected: []
    }),
    methods: {
      newUser () {
        window.alert('Noop')
      },
      searchOnTable () {
        this.searched = searchByContent(this.tasks, this.search)
      },
      getDaySummary () {
        // 获取对应天数的数据
        let day = this.day.format(this.GLOBAL.formatDate2)
        /* 获取统计信息，已完成和所有任务 */
        let result = queryCount(day)
        result.all.then((response) => {
          this.all = response
        })
        result.done.then((response) => {
          this.done = response
        })
        /* 获取任务列表 */
        queryDaySummary(day).then((response) => {
          // 查询成功
          this.tasks = response
          this.searched = this.tasks
        }).catch((error) => {
          this.$refs.message.message({content: '由于异常原因，获取任务列表失败', position: 'center', showMsg: true})
          throw error
        })
        /* 获取未完成任务列表 */
        queryNotDoneTask(day).then((response) => {
          this.notDoneTasks = response
        }).catch((error) => {
          this.$refs.message.message({content: '由于异常原因，获取未完成任务列表失败', position: 'center', showMsg: true})
          throw error
        })
      },
      onSelect (items) {
        this.selected = items
      },
      getAlternateLabel (count) {
        return `${count} 个未完成任务被选择了，点击将其作为明天任务`
      },
      /**
       * 将未完成的任务添加到下一天,需要注意的是当某个任务不是一天之内完成的，添加到明天时，会将该任务的开始时间和结束时间都定为明天
       */
      addNotDoneTasksToTomorrow () {
        //  修改别选择的为完成任务的startTime，endTime
        this.selected.forEach((element, index, array) => {
          // element: 指向当前元素的值
          // index: 指向当前索引
          // array: 指向Array对象本身
          // 修改startTime,endTime
          // todo 这里可能要考虑深拷贝和浅拷贝的问题
          let now = new Date()
          element.startTime = new Date(element.startTime)
          element.endTime = new Date(element.endTime)
          element.startTime.setDate(now.getDate() + 1)
          element.endTime.setDate(now.getDate() + 1)
          element.date = element.startTime.format(this.GLOBAL.formatDate2)
        })
        // 调用TaskService
        bulkAddTasks(this.selected).then((response) => {
          this.$refs.mes.message({content: '添加未完成任务到明天成功', position: 'center', showMsg: true})
          // todo 后台同步
        }).catch((error) => {
          this.$refs.mes.message({content: '由于异常原因，添加为完成任务到明天失败', position: 'center', showMsg: true})
          throw error
        })
        // todo 清空选择,可以先不做
      }
    },
    created () {
      // this.searched = this.tasks
    },
    mounted () {
      // 获取对应天数的数据
      this.getDaySummary()
    }
  }
</script>

<style lang="less" scoped>

  .el-date-editor.el-input, .el-date-editor.el-input__inner {
    width: 100%;
  }
</style>
